package io.terminus.spzx.pay.service.impl;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.alipay.api.response.AlipayTradeWapPayResponse;
import io.terminus.spzx.common.config.exception.SpzxCustomException;
import io.terminus.spzx.model.entity.pay.PaymentInfo;
import io.terminus.spzx.model.vo.common.ResultCodeEnum;
import io.terminus.spzx.pay.properties.AlipayProperties;
import io.terminus.spzx.pay.service.AlipayService;
import io.terminus.spzx.pay.service.PaymentService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author lichunlong lcl253137@alibaba-inc.com
 * @Desc 支付宝Service接口实现类
 * @Date 2025-01-04
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class AlipayServiceImpl implements AlipayService {

    private final PaymentService paymentService;

    private final AlipayClient alipayClient;

    private final AlipayProperties alipayProperties;

    @Override
    public String submitAlipay(String orderNo) {
        // 保存支付记录
        PaymentInfo paymentInfo = paymentService.savePaymentInfo(orderNo);

        //创建API对应的request
        AlipayTradeWapPayRequest alipayRequest = new AlipayTradeWapPayRequest();
        // 同步回调
        alipayRequest.setReturnUrl(alipayProperties.getReturnPaymentUrl());
        // 异步回调
        alipayRequest.setNotifyUrl(alipayProperties.getNotifyPaymentUrl());

        // 准备请求参数，声明Map集合
        Map<String, Object> map = new HashMap<>();
        map.put("out_trade_no", paymentInfo.getOrderNo());
        map.put("product_code", "QUICK_WAP_WAY");
        map.put("total_amount", paymentInfo.getAmount());
        map.put("subject", paymentInfo.getContent());
        alipayRequest.setBizContent(JSON.toJSONString(map));

        AlipayTradeWapPayResponse response;
        try {
            // 发送请求
            response = alipayClient.pageExecute(alipayRequest);
            if (response.isSuccess()) {
                log.info("调用成功");
                return response.getBody();
            } else {
                log.info("调用失败");
                throw new SpzxCustomException(ResultCodeEnum.DATA_ERROR);
            }
        } catch (Exception e) {
            log.error(e.getMessage());
            throw new SpzxCustomException(ResultCodeEnum.DATA_ERROR);
        }
    }
}
